<template>
  <el-container  style="height:100%">
    <el-main style="height:100%">
      用户名称：
			<el-input v-model="SearchParam.UserName" clearable placeholder="请输入用户名称" style="width: 200px; margin-right: 10px"/> 
      手机号：
			<el-input v-model="SearchParam.TelNo" clearable placeholder="请输入手机号码" style="width: 200px; margin-right: 10px"/> 
      <el-button type="primary" @click="queryUserList(SearchParam)">搜索</el-button>
      <el-button type="success" @click="setAddPop(true)">添加</el-button>
      <el-table v-loading="Loading" :data="tableList" border stripe highlight-current-row style="width: 100%; margin: 20px 0 20px 0">
				<el-table-column label="账号" prop="UserID" align="center" width="150">
					<template  #default="scope">
						<span>{{ scope.row.UserID }}</span>
					</template>
				</el-table-column>
				<el-table-column label="用户名称" prop="UserName" align="center" width="150">
					<template  #default="scope">
						<span>{{ scope.row.UserName }} </span>
					</template>
				</el-table-column>
				<el-table-column label="电话" prop="TelNo" align="center" width="150">
					<template  #default="scope">
						<span>{{ scope.row.TelNo }} </span>
					</template>
				</el-table-column>
				<el-table-column label="邮箱" prop="Email" align="center">
					<template  #default="scope">
						<span>{{ scope.row.Email }} </span>
					</template>
				</el-table-column>
				<el-table-column label="角色" prop="UserStatus" align="center" width="200">
					<template  #default="scope">
						<span>{{ scope.row.RoleName }} </span>
					</template>
				</el-table-column>
				<el-table-column label="用户状态" prop="UserStatus" align="center" width="100">
					<template  #default="scope">
						<span>{{ scope.row.UserStatus }} </span>
					</template>
				</el-table-column>
				<el-table-column align="center" label="设置" width="500">
				  <template #default="{ row, column, $index }">
						<el-button size="small" text @click="setUpdatePop(true,row)">修改信息</el-button>
						<el-button size="small" text @click="setStatePop(true,row)">修改状态</el-button>
						<el-button size="small" text @click="deleteUser(row)">删除</el-button>
						<el-button size="small" text @click="setRolePop(true,row)">设置角色</el-button>
					</template> 
				</el-table-column>
			</el-table>
			<el-row>
				<div class="pagination-container">
					<el-col :span="24">
						<el-pagination
							:current-page="queryParams.current"
							:page-sizes="[10, 20, 30, 50]"
							:page-size="queryParams.limit"
							:total="queryParams.total"
							layout="total, sizes, prev, pager, next, jumper"
							prev-text="上一页"
							next-text="下一页"
							background
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
						/>
					</el-col>
				</div>
			</el-row>
    </el-main>
	   
		<!-- 修改信息弹窗 -->
		<el-dialog v-model="showUpdatePop"  title="修改信息" width="500px">
	    <updataAccount :UserInfo="UserInfo" @setUpdatePop="setUpdatePop" @refresh="queryUserList"/>
	  </el-dialog>

    <!-- 修改状态弹窗 -->
		<el-dialog v-model="showStatePop"  title="修改状态" width="500px">
	    <updateStatepop :UserInfo="UserInfo" @closePop="setStatePop" @refresh="queryUserList"/>
	  </el-dialog>

     <!-- 设置角色弹窗 -->
		<el-dialog v-model="showRolePop"  title="修改角色" width="500px">
	    <updateRole :UserInfo="UserInfo" :UserRoles="Role.UserRoles" @close="setRolePop"/>
	  </el-dialog>

      <!-- 新增用户弹窗 -->
		<el-dialog v-model="showAddPop"  title="新增用户" width="500px">
	    <addUser :UserRoles="Role.UserRoles" @close="setAddPop" @refresh="queryUserList"/>
	  </el-dialog>
  </el-container>
</template>


<script lang="ts" setup>
// 平台-平台
import { storeToRefs } from 'pinia';
import { httpReqeustApi } from '/@/api/linxyun/base';
import { useUserInfo } from '/@/stores/userInfo';
 
import { ElMessage, ElMessageBox } from 'element-plus';

import updataAccount from './sys/updataAccount.vue'
import updateStatepop from './sys/updateStatepop.vue'
import updateRole from './sys/updateRole.vue'
import addUser from './sys/addUser.vue'

const httpReqeust = httpReqeustApi();
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);

let state =reactive({
	// 搜索参数
  SearchParam:{
    UserName:'',
    TelNo:''
  },
	// 表格数据加载状态
  Loading:false,
	// 查询参数配置
  queryParams: {
		current: 1,
		limit: 20,
		total: 0
	},
	// 表格数据
	tableList:[] as any [],
	// 角色
	Role:{
		UserRoles:[] as any[],
		OtherRoles:[] as any[]
	},
	// 是否展示修改信息弹窗
	showUpdatePop:false,
  // 是否显示修改状态弹窗
  showStatePop:false,
  // 是否显示修改角色弹窗
  showRolePop:false,
  showAddPop:false,
	UserInfo:{
		UserID:'',
		UserName:'',
    TelNo:'',
    Email:'',
    RoleCodes:''
	}
})
const { SearchParam ,Loading,queryParams,tableList,Role,showUpdatePop,UserInfo,showStatePop,showRolePop,showAddPop} = toRefs(state);

onMounted(() => {
	 queryUserList()
})

/**
 * @description: 设置（打开关闭）用户信息弹窗
 */
const setUpdatePop =(value:boolean,Userinfo?:any)=>{
	state.showUpdatePop=value 
  if(Userinfo){
    UserInfo.value.UserID=Userinfo.UserID
    UserInfo.value.UserName=Userinfo.UserName
    UserInfo.value.TelNo=Userinfo.TelNo
    UserInfo.value.Email=Userinfo.Email
  }
}

/**
 * @description: 设置（打开关闭）用户状态弹窗
 */
const setStatePop =(value:boolean,Userinfo?:any)=>{
	state.showStatePop=value 
  if(Userinfo){
    UserInfo.value.UserID=Userinfo.UserID
  }
}

/**
 * @description: 设置（打开关闭）角色修改弹窗
 */
const setRolePop = (value:boolean,Userinfo?:any)=>{
  state.showRolePop=value 
  if(Userinfo){
    UserInfo.value.UserID=Userinfo.UserID
    UserInfo.value.RoleCodes=Userinfo.RoleCodes
  }
}

/**
 * @description: 设置（打开关闭）新增用户弹窗
 */
const setAddPop = (value:boolean)=>{
  state.showAddPop=value 
}
/**
 * @description: 查询管理员列表
 */
const queryUserList = async (seachParms?:any)=>{
	// 表格数据加载状态
  state.Loading = true
	const params = {
		CustomerID: userInfos.value?.CustomerID,
		CustomerType: 0,
		...seachParms,
		current:queryParams.value.current,
		limit:queryParams.value.limit
	}
	if(params.Phone == ''){
		delete params.Phone
	}
	if(params.UserName == ''){
		delete params.UserName
	}
	// 发送请求查询管理员列表
	httpReqeust.Post('queryUserList',params).then((result:any) => {
	  if(result.code='0000' && result.Records){
      state.tableList=result.Records
			queryParams.value.total = parseInt(result.TotalSize)
		} 
    queryUserRole()
		state.Loading = false
	}).catch((err) => {
		ElMessage({
		  type: 'error',
			message: '查询用户信息失败',
		});
	});
}

/**
 * @description: 查询用户角色信息
 */
const queryUserRole = async ()=>{
	// 发送请求查询角色列表
	httpReqeust.Post('queryRole').then((result:any) => {
		if (result.code=='0000' && result.Records) {
      // 首先先清除角色,防止角色重复
      Role.value.UserRoles=[]
      Role.value.OtherRoles=[]

      for (const item of result.Records) {
				if (item.SubSys === BASE_API.SubSysID) {
					Role.value.UserRoles.push(item)
				} else {
					Role.value.OtherRoles.push(item)
				}
			}
			for (let i = 0; i < tableList.value.length; i++) {
			  let RoleName = ''
				const RoleCodes = [] as any[]
				for (let j = 0; j < Role.value.UserRoles.length; j++) {
					if (tableList.value[i].UserRoles.indexOf(Role.value.UserRoles[j].RoleCode) !== -1) {
						RoleName += Role.value.UserRoles[j].RoleName + ','
						RoleCodes.push(Role.value.UserRoles[j].RoleCode) 
					}
				}
				if (RoleName[RoleName.length - 1] === ',') {
					RoleName = RoleName.slice(0, RoleName.length - 1)
				}	
				tableList.value[i]['RoleName']=RoleName
				tableList.value[i]['RoleCodes']=RoleCodes
				addUserStatus()
			}
		}else{
			ElMessage({
		    type: 'error',
			  message: '未查询到角色信息',
		  });
		}
	}).catch((err:any) => {
		ElMessage({
		  type: 'error',
			message: '查询角色信息信息失败',
		});
	});
}
/**
 * @description: 添加用户状态
 */
const addUserStatus = () =>{
  tableList.value.forEach((item) => {
		switch (item.UserStatus) {
			case '0':
				item.UserStatus = '正常'
				break
			case '3':
				item.UserStatus = '暂停'
				break
			case '9':
				item.UserStatus = '注销'
				break
		}
	})
}
/**
 * @description: 删除用户
 */
const deleteUser = (user:any) =>{
	ElMessageBox.confirm(
    '此操作将永久删除改用户，是否继续',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    sentDeleteReq(user)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * @description: 发送删除用户的请求
 */
const sentDeleteReq =(param:any)=>{
	const finallyParam ={
		UserID:param.UserID,
    EntCode:param.EntCode,
    CustomerType:0,
    CustomerID:0,
	}
  httpReqeust.Post('deleteUser',finallyParam).then((result:any) => {
		if(result.msg === 'success' && result.code== '0000'){
			ElMessage({
		    type: 'success',
			  message: '删除成功',
		  });
			queryUserList()
		}else{
			ElMessage({
		    type: 'error',
			  message: '删除失败',
		  });
		}
	}).catch((err) => {
		ElMessage({
		  type: 'error',
			message: '删除失败',
		});
	});
}

/**
 * @description: 处理每页条数的变化
 */
const handleSizeChange = (size:number)=>{
	queryParams.value.limit = size
	queryUserList()
}
/**
 * @description: 处理上下一页
 */
const handleCurrentChange =(current:number)=>{
  queryParams.value.current = current
	queryUserList()
}
</script>
<style>
  
</style>